<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { ElButton, ElMessage, ElMessageBox, ElPopover } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Detail from './components/Detail.vue'
import { Table } from '@/components/Table'
import {
  saleIndex,
  saleDEL,
  purchaseSubmit,
  purchasePassed,
  goodsSelect,
  transportSelect,
  placestartSelect,
  getPayTypeList,
  saleExportSubmit,
  getStatusList
} from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { purchaseType } from '@/api/common/types'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ref, reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id

const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}
const { t } = useI18n()

// defineOptions({
//   name: 'PurchaseOrder'
// })

const { push } = useRouter()

const { register, tableObject, methods } = useTable<purchaseType>({
  getListApi: saleIndex,
  delListApi: saleDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    title: ''
  },
  find: userRlues.includes('201') ? -1 : userId
})

const { getList, setSearchParams } = methods
getList()

const { emitter } = useEmitt()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'id',
    label: t('warehousingEntry.number'),
    search: {
      show: false
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'sale_no',
    label: '销售单号',
    width: '120px',
    type: 'sale_no',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'goodsTypeName',
    label: t('warehousingEntry.typeOfGoods'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await goodsSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('goodsSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'transport',
    label: t('warehousingEntry.modeOfTransport'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await transportSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('transportSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'placestart',
    label: t('warehousingEntry.origin'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'shouhuo',
    label: t('purchaseOrderAddWrite.recipient'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'placeend',
    label: t('warehousingEntry.destination'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'taxrate',
    label: t('shippingOrderSettings.taxRate'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'remark',
    label: t('warehousingEntry.productNameRemarks'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'buytime',
    label: t('warehousingEntry.receivingDate'),
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        type: 'date'
      }
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'paytype_text',
    label: t('warehousingEntry.paymentType'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await getPayTypeList({})
        let list: any = []
        for (let key in res.data) {
          list.push({
            label: res.data[key],
            value: key
          })
        }
        localStorage.setItem('payTypeListData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'servicefee',
    label: t('warehousingEntry.serviceCharge'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'freight',
    label: t('warehousingEntry.collectionOfFreight'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'rebate',
    label: t('warehousingEntry.factoryRebate'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'chajia',
    label: t('warehousingEntry.priceDifferenceOfGoods'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'status_text',
    label: t('purchaseOrder.auditStatus'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await getStatusList({})
        let list: any = []
        for (let key in res.data) {
          list.push({
            label: res.data[key],
            value: key
          })
        }
        localStorage.setItem('statusListData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'freight_receive',
    label: t('invoice.accountsReceivable'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'total_sale',
    label: t('invoice.totalSales'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'action',
    width: '80px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

// const AddAction = () => {
//   push('/logistics/purchaseOrderAdd')
// }

const delLoading = ref(false)
const getArr = (selections) => {
  let a = ''
  selections.map((v) => (a += v.id + ','))
  return a
}

const delData = async (row: purchaseType | null, multiple: boolean, rlus: string) => {
  if (!checkRlues(rlus)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? getArr(selections) : (tableObject.currentRow?.id as string),
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}
const dialogTitle = ref('')
const dialogVisible = ref(false)

const action = async (row: purchaseType, type: string, ruls: string) => {
  if (!checkRlues(ruls)) return false
  switch (type) {
    case 'Edit':
      {
        push(`/salesModule/salesSlip${type}?id=${row.id}`)
      }
      break
    case 'Submit':
      {
        ElMessageBox.confirm(t('common.examineMessage'), t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await purchaseSubmit('' + row.id)
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'Passed':
      {
        ElMessageBox.confirm(`是否${t('purchaseOrder.passedReview')}?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await purchasePassed('' + row.id)
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'detail':
      {
        // dialogTitle.value = '详情'
        // dialogVisible.value = true
        // tableObject.currentRow = row
        push(`/salesModule/salesSlipEdit?id=${row.id}&isDetail=true`)
      }
      break
    default:
      break
  }
}
const userInfo = wsCache.get(appStore.getUserInfo)
console.log(userInfo, '用户信息')
const submitShow = () => {
  return false
}
const excel = async (row, ruls: string) => {
  // if (!checkRlues(ruls)) return false
  console.log(row)
  let res = await saleExportSubmit(row.id)
  console.log(res)
  const href = URL.createObjectURL(res.data)
  const box = document.createElement('a')
  box.download = `销售单-${row.id}.xls`
  box.href = href
  box.click()
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <!-- <ElButton type="primary" @click="AddAction">{{ t('customClearanceForm.export') }}</ElButton> -->
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElPopover placement="right" :width="80" trigger="click">
          <template #reference>
            <ElButton type="primary"> ··· </ElButton>
          </template>
          <div class="btnContent">
            <ElButton type="primary" @click="action(row, 'Edit', '30-2')">
              {{ t('exampleDemo.edit') }}
            </ElButton>
            <ElButton type="success" @click="action(row, 'detail', '30-4')">
              {{ t('router.watch') }}
            </ElButton>
            <ElButton type="danger" @click="delData(row, false, '30-3')">
              {{ t('exampleDemo.del') }}
            </ElButton>
            <ElButton type="primary" @click="excel(row, '30-6')">
              {{ '导出' }}
            </ElButton>
          </div>
        </ElPopover>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Detail :detail-schema="allSchemas.detailSchema" :current-row="tableObject.currentRow" />
  </Dialog>
</template>
<style lang="less" scoped>
.btnContent {
  display: flex;
  flex-direction: column;
  :deep .el-button + .el-button {
    margin-left: 0;
    margin-top: 15px;
  }
}
</style>
